package cn.cvs.controller;

import cn.cvs.pojo.Supplier;
import cn.cvs.service.SupplierService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;

@RequestMapping("/supplier")
@Controller
public class SupplierController {
    @Autowired
    private SupplierService service;
    @RequestMapping("/list")
    public String list(Model model,@RequestParam(required = false) String supCode,@RequestParam(required = false)String supName,@RequestParam(required = false,defaultValue = "1") int pageIndex,@RequestParam(required = false,defaultValue = "3") int pageSize){
        List<Supplier> supplierList = service.getSupplierList(supCode, supName, pageIndex,pageSize);
        int count = service.getListSize(supCode,supName);
        int pageCount = count % pageSize == 0 ? count / pageSize : (count / pageSize) + 1;
        model.addAttribute("list",supplierList);
        model.addAttribute("supCode",supCode);
        model.addAttribute("supName",supName);
        model.addAttribute("count",count);
        model.addAttribute("pageCount",pageCount);
        model.addAttribute("pageIndex",pageIndex);

        return "supplier/supplierList";
    }
    @RequestMapping("/toAdd")
    public String toAdd(Model model){
        model.addAttribute("opr","add");
        return "supplier/addSupplier";
    }
    @RequestMapping("/add")
    public String add(Supplier supplier){
        service.add(supplier);
        return "redirect:/supplier/list";
    }
    @RequestMapping("/info")
    public String info(Model model,int id){
        model.addAttribute("supplier",service.getSupplier(id));
        return "supplier/info";
    }
    @RequestMapping("/toUpdate")
    public String toUpdate(Model model,int id){
        model.addAttribute("opr","update");
        model.addAttribute("supplier", service.getSupplier(id));
        return "supplier/addSupplier";
    }
    @RequestMapping("/update")
    public String update(Model model,Supplier supplier){
        service.modify(supplier);
        return "redirect:/supplier/list";
    }
    @RequestMapping("/delete")
    public String delete(Model model,int id){
        service.delete(id);
        return "redirect:/supplier/list";
    }
}
